# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
import os
import uuid


import threading
import time
from tqdm import tqdm

import datetime


# Create your models here.
# Define user directory path
def user_directory_path(instance, filename):
    ext = filename.split(".")[-1]
    filename = "{}.{}".format(uuid.uuid4().hex[:10], ext)
    return os.path.join("files", filename)


# Create your models here.
class Task(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200)
    description = models.TextField()
    completed = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    finished = models.DateTimeField(null=True, blank=True)
    train_data_file = models.FileField(upload_to=user_directory_path, null=True)
    gold_data_file = models.FileField(upload_to=user_directory_path, null=True)
    result_data_file = models.FileField(upload_to=user_directory_path, null=True)
    # inference_file = models.FileField(upload_to=user_directory_path, null=True)

    def __str__(self):
        return self.title

    def run(self):
        thread = threading.Thread(target=test_processing, args=(self,))
        thread.start()
        pass


def test_processing(task: Task):
    for i in tqdm(range(15), desc=f"processing {task.title}"):
        time.sleep(1)
    task = Task.objects.get(id=task.id)
    print(f"gold data file = { task.gold_data_file}")
    print(f"train data file = { task.train_data_file}")

    task.finished = datetime.datetime.now()
    task.completed = True
    from apps.home.abc.worker import handle

    output_dir = handle(task.train_data_file.name, task.gold_data_file.name, size=10)
    task.result_data_file = output_dir
    task.save()

    print(f"finished {task.title}")
